<?php

$PWD=dirname(__FILE__);
$VXP_BIN="$PWD/../../vxp";
$XGRAMMAR_JAR="$PWD/xgrammar/dist/xgrammar.jar";

if (!is_file($VXP_BIN))
    die("Oops: Could not find 'vxp' at $VXP_BIN. Did you forget to run 'make'?\n");

if (!is_file($XGRAMMAR_JAR))
    die("Oops: Could not find 'xgrammar.jar' at $XGRAMMAR_JAR. Did you forget to run 'make test'?\n");

$vxp="$VXP_BIN --xpath21 --table";
$w3="java -cp \"$PWD/xgrammar/lib/xpath21.jar".PATH_SEPARATOR."$XGRAMMAR_JAR\" xgrammar.Main --table";
$test_file="$PWD/pathx1-tests.xml";
$tests=simplexml_load_file($test_file);
$outdir="results";

if (!empty($argv[1]))
    $outdir=$argv[1];

$pass=0;
$fail=0;
$count=0;
$i=0;
$start=0;
$limit=0;

if (is_file($outdir))
    die("Output directory $outdir is actually a file. Aborting.\n");

if (!is_dir($outdir))
    mkdir($outdir,0777,true);

foreach($tests->test as $test)
{
    $i++;
    $count++;
    $arg=(string)$test['value'];

    if ($i<$start)
        continue;

    if (($limit) && ($i>$limit))
        die("Test limit exceeded.\n");

    $result=0;
    $vxp_out=Array();
    exec($vxp." ".escapeshellarg($arg)." 2>&1",$vxp_out,$result);

    if ($result)
    {
        print "[FAILED] [$i] [vxp] $arg\n";
        $fail++;
        file_put_contents("$outdir/$i.vxp",$arg."\n");
        file_put_contents("$outdir/$i.vxp",implode("\n",$vxp_out),FILE_APPEND);
        continue;
    }

    $w3_out=Array();
    exec($w3." ".escapeshellarg($arg)." 2>&1",$w3_out,$result);

    if ($result)
    {
        print "[FAILED] [$i] [w3] $arg\n";
        $fail++;
        file_put_contents("$outdir/$i.w3",$arg."\n");
        file_put_contents("$outdir/$i.w3",implode("\n",$w3_out),FILE_APPEND);
        continue;
    }

    $diff=array_diff($w3_out,$vxp_out);
    if (empty($diff))
    {
        print "[SUCCESS] [$i] $arg\n";
        $pass++;
    }
    else
    {
        print "[FAILED] [$i] $arg\n";
        $fail++;

        file_put_contents("$outdir/$i.vxp",$arg."\n");
        file_put_contents("$outdir/$i.vxp",implode("\n",$vxp_out),FILE_APPEND);
        file_put_contents("$outdir/$i.w3",$arg."\n");
        file_put_contents("$outdir/$i.w3",implode("\n",$w3_out),FILE_APPEND);
    }
}

print "--------------------\n";
print "PASSED: $pass/$count (".number_format(($pass/(float)$count)*100,0)."%)\n";
print "FAILED: $fail/$count (".number_format(($fail/(float)$count)*100,0)."%)\n";

